/**
 * java多线程模式
 * @author andy.rong
 */

package com.myjavalab.thread;

public class ThreadPerMessagePattern {

	public static void main(String[] args) {
		System.out.println("Main Begin");
		Host host = new Host();
		host.request(10, 'A');
		host.request(20, 'B');
		host.request(30, 'C');
		System.out.println("Main End");
	}
}

class Host {
	private final Helper helper = new Helper();
	public void request(final int count, final char c) {
		System.out.println("		request(" + count + "," + c + ") Begin");
		new Thread() {
			public void run() {
				helper.handle(count, c);
			}
		}.start();
		System.out.println("		request(" + count + "," + c + ") End");
	}

	/* Q 7-2
	 * 
	public void request(final int count, final char c) {
		System.out.println("		request(" + count + "," + c + ") Begin");
		helper.handle(count, c);
		System.out.println("		request(" + count + "," + c + ") End");
	}
	 */
	
	/* Q 7-4
	 * 
	 public void request(final int count, final char c) {
		System.out.println("		request(" + count + "," + c + ") Begin");
		new HelperThread(helper, count, c).start();
		System.out.println("		request(" + count + "," + c + ") End");
	}
	 */
	
}

class Helper {
	public void handle(int count, char c) {
		System.out.println("		handle(" + count + "," + c + ") Begin");
		for(int i = 0; i < count; i++) {
			slowly();
			System.out.print(c);
		}
		System.out.println("");
		System.out.println("		handle(" + count + "," + c + ") End");
	}
	
	private void slowly() {
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
		}
	}
}

class HelperThread extends Thread{
	private final Helper helper;
	private final int count;
	private final char c;
	
	public HelperThread(Helper helper, int count, char c) {
		this.helper = helper;
		this.count = count;
		this.c = c;
	}
	
	public void run() {
		helper.handle(count, c);
	}
}